<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCampfireStore } from '../stores/campfireStore'
import { useContainerStore } from '../stores/containerStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ChatDotRound, Star, Check } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const campfireStore = useCampfireStore()
const containerStore = useContainerStore()

// 获取帖子ID
const postId = route.params.id

// 帖子数据
const post = computed(() => campfireStore.getPostById(postId))

// 回复列表
const replies = computed(() => campfireStore.getRepliesByPostId(postId))

// 新回复内容
const newReply = ref({
  content: '',
  isExperience: false
})

// 回复表单引用
const replyFormRef = ref(null)

// 回复表单规则
const replyRules = {
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

// 创建容器对话框
const createContainerDialog = ref(false)
const selectedReplyId = ref('')
const containerForm = ref({
  name: '',
  description: '',
  category: '',
  estimatedTime: 30
})

// 容器表单引用
const containerFormRef = ref(null)

// 容器表单规则
const containerRules = {
  name: [{ required: true, message: '请输入容器名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 分类选项
const categoryOptions = [
  { value: 'work', label: '工作' },
  { value: 'study', label: '学习' },
  { value: 'life', label: '生活' },
  { value: 'other', label: '其他' }
]

// 检查帖子是否存在
onMounted(() => {
  if (!post.value) {
    ElMessage.error('帖子不存在')
    router.push('/campfire')
  }
})

// 提交回复
function submitReply() {
  replyFormRef.value.validate((valid) => {
    if (valid) {
      campfireStore.createReply({
        postId: postId,
        content: newReply.value.content,
        isExperience: newReply.value.isExperience
      })
      
      // 清空表单
      newReply.value.content = ''
      newReply.value.isExperience = false
      
      ElMessage.success('回复成功')
    }
  })
}

// 点赞回复
function likeReply(replyId) {
  campfireStore.likeReply(replyId)
}

// 采纳为最佳答案
function acceptReply(replyId) {
  // 如果已有最佳答案，先确认是否更换
  if (post.value.acceptedReplyId && post.value.acceptedReplyId !== replyId) {
    ElMessageBox.confirm(
      '你已经采纳了一个最佳答案，是否更换？',
      '更换最佳答案',
      {
        confirmButtonText: '确认更换',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      campfireStore.acceptReply(postId, replyId)
      ElMessage.success('已更换最佳答案')
    }).catch(() => {})
  } else {
    campfireStore.acceptReply(postId, replyId)
    ElMessage.success('已采纳为最佳答案')
    
    // 询问是否创建容器验证解决方案
    ElMessageBox.confirm(
      '是否为此解决方案创建一个新的「时间容器」进行尝试？',
      '创建验证容器',
      {
        confirmButtonText: '创建容器',
        cancelButtonText: '暂不创建',
        type: 'info'
      }
    ).then(() => {
      // 打开创建容器对话框
      selectedReplyId.value = replyId
      openCreateContainerDialog(replyId)
    }).catch(() => {})
  }
}

// 打开创建容器对话框
function openCreateContainerDialog(replyId) {
  const reply = replies.value.find(r => r.id === replyId)
  if (reply) {
    // 预填表单
    containerForm.value.name = `验证：${post.value.title.replace('求助：', '')}`
    containerForm.value.description = `验证社区中的解决方案：${reply.content.substring(0, 50)}${reply.content.length > 50 ? '...' : ''}`
    containerForm.value.category = 'study' // 默认分类
    containerForm.value.estimatedTime = 30 // 默认30分钟
    
    createContainerDialog.value = true
  }
}

// 创建验证容器
function createVerificationContainer() {
  containerFormRef.value.validate((valid) => {
    if (valid) {
      // 创建容器
      const containerId = containerStore.createContainer({
        name: containerForm.value.name,
        description: containerForm.value.description,
        category: containerForm.value.category,
        estimatedTime: containerForm.value.estimatedTime,
        tags: post.value.tags, // 使用帖子的标签
        relatedPostId: postId, // 关联帖子ID
        relatedReplyId: selectedReplyId.value // 关联回复ID
      })
      
      // 关闭对话框
      createContainerDialog.value = false
      
      // 提示成功
      ElMessage.success('验证容器创建成功')
      
      // 询问是否立即开始专注
      ElMessageBox.confirm(
        '容器已创建成功，是否立即开始专注？',
        '开始专注',
        {
          confirmButtonText: '立即开始',
          cancelButtonText: '稍后再说',
          type: 'info'
        }
      ).then(() => {
        // 跳转到容器页面并开始专注
        router.push(`/container?id=${containerId}&autoStart=true`)
      }).catch(() => {
        // 仅跳转到容器页面
        router.push('/container')
      })
    }
  })
}

// 返回上一页
function goBack() {
  router.back()
}

// 格式化时间
function formatDate(timestamp) {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化投入时间
function formatInvestedTime(minutes) {
  if (minutes < 60) {
    return `${minutes}分钟`
  } else {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`
  }
}
</script>

<template>
  <div class="post-detail-container" v-if="post">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h1 class="page-title">探索营地 - 帖子详情</h1>
    </div>
    
    <!-- 帖子内容 -->
    <div class="post-content">
      <div class="post-header">
        <h2 class="post-title">{{ post.title }}</h2>
        <div class="post-meta">
          <div class="post-time">发布于 {{ formatDate(post.createdAt) }}</div>
          <div class="invested-time" v-if="post.investedTime > 0">
            <el-tag type="warning" effect="plain">已探索 {{ formatInvestedTime(post.investedTime) }}</el-tag>
          </div>
        </div>
      </div>
      
      <div class="post-tags">
        <el-tag 
          v-for="tag in post.tags" 
          :key="tag"
          size="small"
          effect="plain"
          class="tag-item"
        >
          {{ tag }}
        </el-tag>
      </div>
      
      <div class="post-description">
        <h3>问题描述</h3>
        <p>{{ post.description }}</p>
      </div>
      
      <div class="post-blocking-point">
        <h3>卡点描述</h3>
        <p>{{ post.blockingPoint }}</p>
      </div>
    </div>
    
    <!-- 最佳答案 -->
    <div class="best-answer" v-if="post.acceptedReplyId">
      <div class="best-answer-header">
        <h3>
          <el-icon><Star /></el-icon>
          最佳解决方案
        </h3>
      </div>
      
      <div class="reply-item best-reply" v-if="replies.find(r => r.id === post.acceptedReplyId)">
        <div class="reply-content">
          <div class="reply-badge" v-if="replies.find(r => r.id === post.acceptedReplyId).isExperience">
            <el-tag type="success">经验分享</el-tag>
          </div>
          <p>{{ replies.find(r => r.id === post.acceptedReplyId).content }}</p>
        </div>
        
        <div class="reply-footer">
          <div class="reply-meta">
            <span class="reply-author">{{ replies.find(r => r.id === post.acceptedReplyId).authorName || '匿名用户' }}</span>
            <span class="reply-time">{{ formatDate(replies.find(r => r.id === post.acceptedReplyId).createdAt) }}</span>
          </div>
          
          <div class="reply-actions">
            <el-button 
              size="small" 
              :type="replies.find(r => r.id === post.acceptedReplyId).isLiked ? 'primary' : 'default'" 
              @click="likeReply(post.acceptedReplyId)"
              :icon="Star"
              text
            >
              {{ replies.find(r => r.id === post.acceptedReplyId).likes || 0 }}
            </el-button>
            
            <el-button 
              size="small" 
              type="success" 
              @click="openCreateContainerDialog(post.acceptedReplyId)"
              plain
            >
              创建验证容器
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 回复列表 -->
    <div class="replies-section">
      <div class="replies-header">
        <h3>
          <el-icon><ChatDotRound /></el-icon>
          全部回复 ({{ replies.length }})
        </h3>
      </div>
      
      <div class="replies-list" v-if="replies.length > 0">
        <div 
          v-for="reply in replies" 
          :key="reply.id"
          class="reply-item"
          :class="{ 'is-accepted': reply.id === post.acceptedReplyId }"
          v-show="reply.id !== post.acceptedReplyId"
        >
          <div class="reply-content">
            <div class="reply-badge" v-if="reply.isExperience">
              <el-tag type="success">经验分享</el-tag>
            </div>
            <p>{{ reply.content }}</p>
          </div>
          
          <div class="reply-footer">
            <div class="reply-meta">
              <span class="reply-author">{{ reply.authorName || '匿名用户' }}</span>
              <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
            </div>
            
            <div class="reply-actions">
              <el-button 
                size="small" 
                :type="reply.isLiked ? 'primary' : 'default'" 
                @click="likeReply(reply.id)"
                :icon="Star"
                text
              >
                {{ reply.likes || 0 }}
              </el-button>
              
              <el-button 
                size="small" 
                type="primary" 
                @click="acceptReply(reply.id)"
                :icon="Check"
                plain
                v-if="!post.acceptedReplyId || post.acceptedReplyId !== reply.id"
              >
                采纳为最佳
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="empty-replies" v-else>
        <el-empty description="暂无回复" />
      </div>
    </div>
    
    <!-- 发表回复 -->
    <div class="reply-form">
      <h3>发表回复</h3>
      
      <el-form 
        ref="replyFormRef"
        :model="newReply"
        :rules="replyRules"
      >
        <el-form-item prop="content">
          <el-input 
            v-model="newReply.content" 
            type="textarea" 
            :rows="4"
            placeholder="分享你的解决方案或经验..."
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="newReply.isExperience">这是我的经验分享</el-checkbox>
          <div class="experience-hint">勾选此项表示你分享的是解决类似问题的个人经验和方法论，而非直接解答</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitReply">发表回复</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 创建验证容器对话框 -->
    <el-dialog
      v-model="createContainerDialog"
      title="创建验证容器"
      width="500px"
    >
      <el-form 
        ref="containerFormRef"
        :model="containerForm"
        :rules="containerRules"
        label-position="top"
      >
        <el-form-item label="容器名称" prop="name">
          <el-input v-model="containerForm.name" placeholder="请输入容器名称" />
        </el-form-item>
        
        <el-form-item label="容器描述" prop="description">
          <el-input 
            v-model="containerForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入容器描述"
          />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="containerForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="预估时间（分钟）">
          <el-input-number v-model="containerForm.estimatedTime" :min="5" :step="5" style="width: 100%" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createContainerDialog = false">取消</el-button>
          <el-button type="primary" @click="createVerificationContainer">创建容器</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.post-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  margin: 0 0 0 20px;
  font-size: 24px;
}

.post-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.post-header {
  margin-bottom: 15px;
}

.post-title {
  margin: 0 0 10px;
  font-size: 22px;
  line-height: 1.4;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 0;
}

.post-description, .post-blocking-point {
  margin-bottom: 20px;
}

.post-description h3, .post-blocking-point h3 {
  font-size: 16px;
  margin: 0 0 10px;
  color: #606266;
}

.post-description p, .post-blocking-point p {
  margin: 0;
  line-height: 1.6;
  white-space: pre-line;
}

.best-answer {
  background-color: #f0f9eb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  border: 1px solid #e1f3d8;
}

.best-answer-header {
  margin-bottom: 15px;
}

.best-answer-header h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  color: #67c23a;
  font-size: 18px;
}

.replies-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.replies-header {
  margin-bottom: 20px;
}

.replies-header h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
}

.replies-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.reply-item {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.reply-item:last-child {
  border-bottom: none;
}

.best-reply {
  border: none;
  padding-bottom: 0;
}

.reply-content {
  margin-bottom: 10px;
}

.reply-badge {
  margin-bottom: 10px;
}

.reply-content p {
  margin: 0;
  line-height: 1.6;
  white-space: pre-line;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reply-meta {
  color: #909399;
  font-size: 14px;
}

.reply-author {
  font-weight: 500;
  margin-right: 10px;
}

.reply-actions {
  display: flex;
  gap: 10px;
}

.reply-form {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.reply-form h3 {
  margin: 0 0 20px;
  font-size: 18px;
}

.experience-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.empty-replies {
  padding: 30px 0;
  text-align: center;
}

.is-accepted {
  background-color: #f0f9eb;
  border-radius: 4px;
}
</style>